#include <d3d9.h>
#include <d3dx9.h>
#include "customVertex.h"
#include "BufferCollection.h"
#include "Constants.h"

// ctor
Minicraft::BufferCollection::BufferCollection(LPDIRECT3DDEVICE9 device)
{
	this->device = device;
	float size = Minicraft::Constants::FACESIZE;
	// define the basic unmodified verticies for a face
	CUSTOMVERTEX vertices[] =
	{
		{-size, size, 0.0f,   0.0f, 0.0f, size,   0.0f, 0.0f },
		{size, size, 0.0f,    0.0f, 0.0f, size,   1.0f, 0.0f },
		{-size, -size, 0.0f,  0.0f, 0.0f, size,   0.0f, 1.0f },
		{size, -size, 0.0f,   0.0f, 0.0f, size,   1.0f, 1.0f }
	};

	// create the indices using an int array
	short indices[] =
	{
		0, 1, 2,    // triangle 1 of side
		1, 3, 2,	// triangle 2 of side
	};

	// a mysterious void pointer
	VOID* pVoid;

	// create the vertex buffer
	this->device->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX),
									0,
									CUSTOMFVF,
									D3DPOOL_MANAGED,
									&(this->vertexBuffer),
									NULL);

	// lock v_buffer and load the vertices into it
	Minicraft::BufferCollection::vertexBuffer->Lock(0, 0, (void**)&pVoid, 0);
	memcpy(pVoid, vertices, sizeof(vertices));
	Minicraft::BufferCollection::vertexBuffer->Unlock();

	// create an index buffer interface called i_buffer
	this->device->CreateIndexBuffer(6*sizeof(short),
									0,
									D3DFMT_INDEX16,
									D3DPOOL_MANAGED,
									&(this->indexBuffer),
									NULL);

	// lock i_buffer and load the indices into it
	this->indexBuffer->Lock(0, 0, (void**)&pVoid, 0);
	memcpy(pVoid, indices, sizeof(indices));
	this->indexBuffer->Unlock();
}


// dtor
Minicraft::BufferCollection::~BufferCollection()
{
	this->vertexBuffer->Release();
	this->indexBuffer->Release();
}

// gets the Direct3d Device
LPDIRECT3DDEVICE9 Minicraft::BufferCollection::GetD3DDevice()
{
	return this->device;
}

// gets the vertex buffer for a face
IDirect3DVertexBuffer9* Minicraft::BufferCollection::GetVertexBuffer()
{
	return this->vertexBuffer;
}

// gets the index buffer for a face
IDirect3DIndexBuffer9* Minicraft::BufferCollection::GetIndexBuffer()
{
	return this->indexBuffer;
}